//
//  PersistenceViewController.m
//  Persistence
//
//  Created by KaiKai on 11-8-20.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//


#import "PersistenceViewController.h"
#import "FourLines.h"

@implementation PersistenceViewController

@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
	
//	NSString *filePath = [self dataFilePath];
//	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
//	{
////		NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
////		field1.text = [array objectAtIndex:0];
////		field2.text = [array objectAtIndex:1];
////		field3.text = [array objectAtIndex:2];
////		field4.text = [array objectAtIndex:3];
////		[array release];
//		
//		NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
//		NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//		FourLines *fourLines = [unarchiver decodeObjectForKey:KDatakey];
//		[unarchiver finishDecoding];
//		
//		field1.text = fourLines.field1;
//		field2.text = fourLines.field2;
//		field3.text = fourLines.field3;
//		field4.text = fourLines.field4;
//		
//		[unarchiver release];
//		[data release];
//	}

	if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK)
	{
		sqlite3_close(database);
		NSAssert(0, @"Failed to open database");
	}
	
	char *errorMsg;
	NSString *createSQL = @"Create table if not exists Fields(Row integer primary key, FiEld_Data text);";
	if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
	{
		sqlite3_close(database);
		NSAssert1(0, @"Error Create table: %s", errorMsg);
	}
	
	NSString *query = @"Select row, field_data from fields order by row";
	sqlite3_stmt *statement;
	if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
	{
		while (sqlite3_step(statement) == SQLITE_ROW) 
		{
			int row = sqlite3_column_int(statement, 0);
			char *rowData = (char *)sqlite3_column_text(statement, 1);
			NSString *fieldName = [[NSString alloc] initWithFormat:@"field%d", row];
			NSString *fieldValue = [[NSString alloc] initWithUTF8String:rowData];
			UITextField *field = [self valueForKey:fieldName];
			field.text = fieldValue;
			[fieldName release];
			[fieldValue release];
		}
		sqlite3_finalize(statement);
	}
	
	UIApplication *app = [UIApplication sharedApplication];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc
{
	[field1 release];
	[field2 release];
	[field3 release];
	[field4 release];
	
	[super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSString *)dataFilePath
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:KFileName];
}

- (void)applicationWillTerminate:(NSNotification *)notification
{
//	NSMutableArray *array = [[NSMutableArray alloc] init];
//	[array addObject:field1.text];
//	[array addObject:field2.text];
//	[array addObject:field3.text];
//	[array addObject:field4.text];
//	[array writeToFile:[self dataFilePath] atomically:YES];
//	[array release];
	
//	FourLines *fourLines = [[FourLines alloc] init];
//	fourLines.field1 = field1.text;
//	fourLines.field2 = field2.text;
//	fourLines.field3 = field3.text;
//	fourLines.field4 = field4.text;
//	NSMutableData *data = [[NSMutableData alloc] init];
//	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//	[archiver encodeObject:fourLines forKey:KDatakey];
//	[archiver finishEncoding];
//	[data writeToFile:[self dataFilePath] atomically:YES];
//	[fourLines release];
//	[archiver release];
//	[data release];
	
	for (int i=1; i<=4; ++i)
	{
		NSString *fieldName = [[NSString alloc] initWithFormat:@"field%d", i];
		UITextField *field = [self valueForKey:fieldName];
		[fieldName release];
		NSString *update = [[NSString alloc] initWithFormat:@"Insert Or Replace Into Fields(Row, Field_Data) Values(%d, '%@');", i, field.text];
		
		char *errorMsg;
		if (sqlite3_exec(database, [update UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
		{
			NSAssert2(0, @"Error updating tables: row=%d %s", i, errorMsg);
			sqlite3_free(errorMsg);
		}
	}
	sqlite3_close(database);
}

@end
